package com.xuhai.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuhai.blog.admin.entity.UserEntity;
import com.xuhai.blog.admin.mapper.UserMapper;
import com.xuhai.blog.admin.service.CodeService;
import com.xuhai.blog.admin.service.ExpiresService;
import com.xuhai.blog.admin.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhai.blog.common.exception.RTException;
import com.xuhai.blog.common.form.LoginForm;
import com.xuhai.blog.common.form.PasswordForm;
import com.xuhai.blog.common.util.ResultJson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 机蜂
 * @since 2022-02-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private CodeService codeService;

    @Autowired
    private ExpiresService expiresService;

    @Value("${adminId}")
    private Integer adminId;

    @Override
    public ResultJson login(LoginForm loginForm) {
        /*判断验证码是否正确*/
        if (!codeService.checkCode(loginForm.getUuid(), loginForm.getCode())) {
            return ResultJson.error("验证码不正确！");
        }
        /*根据用户名查询用户信息*/
        UserEntity loginUser = getUserByUserName(loginForm.getUsername());

        /*加密用户输入的明文密码*/
        String md5Pwd = DigestUtils.md5Hex(loginForm.getPassword());
        /*判断密码是否正确*/
        if (loginUser == null || !md5Pwd.equals(loginUser.getPassword())) {
            return ResultJson.error("用户名或密码不正确！");
        }
        if (loginUser.getStatus() != 1) {
            return ResultJson.error("该账户已被封禁，请联系管理员");
        }
        return expiresService.saveToken(loginUser.getUserId());
    }

    @Override
    public void update(UserEntity user) {
        if(user.getUserId()==null){
            UserEntity searchUser=getUserByUserName(user.getUsername());
            if(searchUser!=null){
                throw new RTException("用户名已存在！");
            }
            user.setPassword(DigestUtils.md5Hex("123456"));
            this.save(user);
        }else{
            this.updateById(user);
        }
    }

    @Override
    public void updatePassword(PasswordForm passwordForm) {
        UserEntity user=this.getById(passwordForm.getUserId());
        if(user == null || !user.getPassword().equals(DigestUtils.md5Hex(passwordForm.getOldPassword()))){
            throw new RTException("原密码不正确！");
        }
        user=passwordForm.toEntity();
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        this.updateById(user);
    }

    @Override
    public IPage<UserEntity> getPage(int page, int limit, UserEntity user) {
        IPage<UserEntity> iPage=this.page(new Page<>(page,limit),
                new QueryWrapper<UserEntity>()
                        .eq(StringUtils.isNotBlank(user.getUsername()),"username",user.getUsername())
                        .like(StringUtils.isNotBlank(user.getNickname()),"nickname",user.getNickname())
                        .eq(user.getStatus()!=null,"status",user.getStatus())
                        .eq(!user.getUserId().equals(adminId),"create_admin",user.getUserId())
                        .or()
                        .eq(!user.getUserId().equals(adminId),"user_id",user.getUserId())
                        .orderByDesc("user_id")
        );
        return iPage;
    }

    private UserEntity getUserByUserName(String username){
        return this.getOne(new QueryWrapper<UserEntity>().eq("username",username));
    }
}
